//
//  ChangeInfoViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/12/6.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "ChangeInfoViewController.h"
#import "WeChatLoginViewController.h"
@interface ChangeInfoViewController ()
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UIButton * headerImgBtn;//头像
@property (nonatomic, strong)UITextField * nameTextField;//姓名
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
@property (nonatomic, strong)NSData * headerImgData;
- (void)ifLogin;
@end

@implementation ChangeInfoViewController(networking)
//保存
- (void)saveChangedInfo{
    NSDictionary * dic = @{
                           @"phone":self.phoneString,
                           @"token":self.tokenString,
                           @"nickname":self.nameString
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"usiosApi/headimg" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (self.headImg != nil) {
            self.headerImgData = UIImageJPEGRepresentation(self.headImg, .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:self.headerImgData name:@"headimg" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {

            int64_t delayInSeconds = 1;// 延迟的时间
            /*
             *@parameter 1,时间参照，从此刻开始计时
             *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
             */
            ShowMessage(@"修改成功");
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self hiddenProgressHUD];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self hiddenProgressHUD];
            [self ifLogin];
        }else{
            [self hiddenProgressHUD];
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}

@end
@implementation ChangeInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"编辑资料";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 100/WIDTH_6_SCALE;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectZero];
        UILabel * bindPhoneNumLab = [[UILabel alloc] initWithFrame:CGRectMake(10/WIDTH_6_SCALE, 10/WIDTH_6_SCALE, 100/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
        [self label:bindPhoneNumLab withFont:DEF_FontSize_14 withText:@"绑定手机号:" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:_headerView];
        UILabel * phoneNumLab = [[UILabel alloc] initWithFrame:CGRectMake(bindPhoneNumLab.right, bindPhoneNumLab.top, SCREEN_WIDTH - bindPhoneNumLab.width - bindPhoneNumLab.left - 10/WIDTH_6_SCALE, bindPhoneNumLab.height)];
        [self label:phoneNumLab withFont:DEF_FontSize_14 withText:[UserModel sharedInstanced].mobile withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentRight withView:_headerView];
        UIView * bindPhoneLineView = [[UIView alloc] initWithFrame:CGRectMake(0, bindPhoneNumLab.bottom + 10/WIDTH_6_SCALE, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        bindPhoneLineView.backgroundColor = getColor(textGrayColor);
        [_headerView addSubview:bindPhoneLineView];
        //头像
        int imgW = 69/WIDTH_6_SCALE;
        self.headerImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 10/WIDTH_6_SCALE - imgW, bindPhoneLineView.bottom + 10/WIDTH_6_SCALE, imgW, imgW)];
        [self.headerImgBtn setImage:self.headImg forState:UIControlStateNormal];
        [self.headerImgBtn addTarget:self action:@selector(headerImgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.headerImgBtn.layer.cornerRadius = imgW/2;
        self.headerImgBtn.layer.masksToBounds = YES;
        [_headerView addSubview:self.headerImgBtn];
        UIView * imgLineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.headerImgBtn.bottom + 10/WIDTH_6_SCALE, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        imgLineView.backgroundColor = getColor(textGrayColor);
        [_headerView addSubview:imgLineView];
        //头像标题
        UILabel * headTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(10/WIDTH_6_SCALE, 0, 40/WIDTH_6_SCALE, self.headerImgBtn.height)];
        headTitleLab.centerY = self.headerImgBtn.centerY;
        [self label:headTitleLab withFont:DEF_FontSize_14 withText:@"头像" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:_headerView];
        //姓名标题
        UILabel * nameTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(headTitleLab.left, imgLineView.bottom + 10/WIDTH_6_SCALE, 80/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
        [self label:nameTitleLab withFont:DEF_FontSize_14 withText:@"昵称：" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:_headerView];
        //姓名
        self.nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(nameTitleLab.right + 10/WIDTH_6_SCALE, nameTitleLab.top, SCREEN_WIDTH - nameTitleLab.right - 20/WIDTH_6_SCALE, nameTitleLab.height)];
        self.nameTextField.placeholder = @"请输入昵称";
        self.nameTextField.textAlignment = NSTextAlignmentRight;
        self.nameTextField.font = DEF_FontSize_14;
        self.nameTextField.text = self.nameString;
        [_headerView addSubview:self.nameTextField];
        UIView * nameLineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.nameTextField.bottom + 10/WIDTH_6_SCALE, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        nameLineView.backgroundColor = getColor(textGrayColor);
        [_headerView addSubview:nameLineView];
        //保存
        int saveBtnLeft = 40/WIDTH_6_SCALE;
        UIButton * saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(saveBtnLeft, nameLineView.bottom + 50/WIDTH_6_SCALE, SCREEN_WIDTH - 2 * saveBtnLeft, 50/WIDTH_6_SCALE)];
        [saveBtn setBackgroundColor:getColor(mainRedColor)];
        [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
        [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        saveBtn.titleLabel.font = DEF_FontSize_14;
        saveBtn.layer.cornerRadius = 6;
        saveBtn.layer.masksToBounds = YES;
        [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:saveBtn];
        _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, saveBtn.bottom + 20/WIDTH_6_SCALE);
    }return _headerView;
}

#pragma mark - action
- (void)headerImgBtnClick:(UIButton *)sender{
    [self selectPoto];
}
- (void)selectPoto{
    //选择头像
    [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
        self.headImg = img;
        [self.headerImgBtn setImage:self.headImg forState:UIControlStateNormal];
    }];
}
- (void)saveBtnClick{
    self.nameString = self.nameTextField.text;
    if ([self.nameString isEqualToString:@""] || [self.nameString length] == 0 || self.nameString == nil) {
        self.nameString = @"";
    }
    [self saveChangedInfo];
}
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    [self presentViewController:navi animated:YES completion:nil];
}
@end
